<template>
  <div style="margin-top: 60px">
    <div v-show="step === 'step-sendCode'">
      <el-form ref="phoneFindPwdForm" :model="phoneFindPwdForm" :rules="phoneLoginRules" auto-complete="false">
        <el-form-item prop="phone">
          <el-input ref="phone" v-model.trim="phoneFindPwdForm.phone" placeholder="手机号" name="phone" type="text" auto-complete="false" />
        </el-form-item>

        <el-form-item prop="code" class="form-item-code">
          <div class="flex">
            <el-input v-model.trim="phoneFindPwdForm.code" maxlength="6" class="flex1" type="text" placeholder="短信验证码" name="code" />
            <SendCode ref="retrieveCode" @run="handleSendCode" />
          </div>
        </el-form-item>
        <el-button type="primary" style="width: 100%; margin: 10px 0 20px" @click="handleCheckPhoneCode"> 下一步 </el-button>
      </el-form>
    </div>

    <div v-show="step === 'step-resetPwd'">
      <el-form ref="setPwdForm" :model="setPwdForm" :rules="setPwdRules" :hide-required-asterisk="true">
        <el-form-item prop="newPassword">
          <el-input v-model.trim="setPwdForm.newPassword" size="medium" type="password" autocomplete="off" placeholder="8-16位且至少包含1个字母，1个数字" />
        </el-form-item>

        <el-form-item prop="repeatPassword">
          <el-input v-model.trim="setPwdForm.repeatPassword" size="medium" type="password" autocomplete="off" placeholder="确认密码" />
        </el-form-item>
        <el-button type="primary" style="width: 100%; margin: 10px 0 20px" @click="handleSave"> 确 定 </el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { validatePhone, validatePassword } from '@/utils/validate.js'
import { loginApi } from '@/api/api.js'
import SendCode from '@/components/SendCode'

export default {
  name: 'FindPwd',
  components: {
    SendCode
  },
  props: {
    redirect: {
      type: String,
      default: '/'
    }
  },
  data() {
    const validateRepeatPassword = (rule, value, callback) => {
      if (value !== this.setPwdForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    return {
      step: 'step-sendCode',
      // 手机验证找回密码表单
      phoneFindPwdForm: {
        phone: '',
        code: ''
      },
      // 设置密码表单
      setPwdForm: {
        newPassword: '',
        repeatPassword: '',
        codeTag: ''
      },
      // 手机验证登录表单验证
      phoneLoginRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { trigger: 'blur', validator: validatePhone }
        ],
        code: [{ required: true, trigger: 'blur', message: '请输入短信验证码' }]
      },
      // 设置密码表单验证
      setPwdRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        repeatPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateRepeatPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 发送短信验证码
    handleSendCode() {
      // this.step = 'step-resetPwd'
      this.$refs.phoneFindPwdForm.validateField('phone', async (valid) => {
        if (!valid) {
          try {
            await this.$request(loginApi.sendPhoneCode, { phone: this.phoneFindPwdForm.phone })
            this.$refs.retrieveCode.start()
            this.$notify({
              title: '成功',
              message: '验证码短信已发送，请及时查收',
              type: 'success'
            })
          } catch (error) {
            console.log('tryCatch', error)
          }
        }
      })
    },
    // 验证手机验证码是否正确
    handleCheckPhoneCode() {
      this.$refs.phoneFindPwdForm.validate(async (valid) => {
        if (valid) {
          const { phone, code } = this.phoneFindPwdForm
          try {
            const res = await this.$request(loginApi.checkPhoneCode, { phone, code })
            // 后续步骤使用该参数验证
            this.setPwdForm.codeTag = res.data.codeTag
            this.step = 'step-resetPwd'
          } catch (error) {
            console.log('tryCatch', error)
          }
        }
      })
    },
    // 保存
    handleSave() {
      this.$refs.setPwdForm.validate(async (valid) => {
        if (valid) {
          const { phone } = this.phoneFindPwdForm
          const { newPassword, codeTag } = this.setPwdForm

          try {
            const res = await this.$request(loginApi.resetPassword, {
              phone,
              newPassword,
              codeTag
            })
            if (res.code === 1) {
              this.$message({
                message: '密码设置成功',
                type: 'success'
              })
              this.$emit('backToLogin')
            }
          } catch (error) {
            console.log('tryCatch', error)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item-code {
  ::v-deep.el-form-item__content {
    background: #fff;
  }
}
</style>
